package com.estasenposse.tdam.RSS;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.estasenposse.tdam.bd.DatabaseHandler;
import com.estasenposse.tdam.entities.Noticia;
import com.estasenposse.tdam.entities.Publicity;
import com.estasenposse.tdam.parsers.RssParserSax;
import com.estasenposse.tdam.services.NoteNotification;
import com.estasenposse.tdam.ui.Main;
import com.example.estasenposse.R;

public class RssReader extends AsyncTask<String, ProgressDialog, Boolean> {

	private List<Noticia> noticias;
	private DatabaseHandler mHelper;
	private Context context;

	private ProgressBar pg_Noteloading;
	private ImageButton image_button;
	private Boolean FLAG_PRIMERAVEZ;
	private Boolean FLAG_SERVICE;

	private List<Publicity> publicidades;
	private SharedPreferences prefs;
	ProgressDialog progressDialog;
	Activity activity;

	public RssReader(Activity activity, Context context) {
		this.context = context;
		FLAG_PRIMERAVEZ = false;
		FLAG_SERVICE = false;

		if (activity != null) {
			this.activity = activity;

			this.pg_Noteloading = (ProgressBar) activity
					.findViewById(R.id.pb_update_notes);

			this.image_button = (ImageButton) activity
					.findViewById(R.id.btn_updateAction);
		} else {
			FLAG_SERVICE = true;
		}
		mHelper = new DatabaseHandler(context);
	}

	@Override
	protected Boolean doInBackground(String... params) {

		try {
			ConnectivityManager connectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connectivityManager
					.getActiveNetworkInfo();
			if (networkInfo != null && networkInfo.isConnected()) {
				RssParserSax saxparser = new RssParserSax(
						"http://www.estasenposse.com/RSS/RSSEstasEnPosse.xml");
				noticias = saxparser.parse();

				if (mHelper.getNoteRowCount() == 0) {
					saveData();
				} else {
					updateData();
				}

				RssParserSax publicitySaxParser = new RssParserSax(
						"http://www.estasenposse.com/RSS/RSSPublicidadEstasEnPosse.xml");
				publicidades = publicitySaxParser.parsePublicity();

				if (mHelper.getPubliRowCount() == 0) {
					savePublicity();
				} else {
					updatePublicity();
				}
			}
			return true;
		} catch (Exception e) {
			Log.e(RssReader.class.getName(), "exception", e);
			return false;
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);

		if (image_button != null) {
			image_button.setVisibility(View.VISIBLE);
		}
		if (pg_Noteloading != null) {
			pg_Noteloading.setVisibility(View.GONE);
		}
		if (FLAG_PRIMERAVEZ == true && FLAG_SERVICE == false) {
			if (mHelper.getNoteRowCount() > 0) {
				((Main) activity).cargarUltimaNota();
			}
			if (mHelper.getPubliRowCount() > 0) {
				((Main) activity).cargarPubli();
			}
		}
		try {
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	public Boolean getFLAG_SERVICE() {
		return FLAG_SERVICE;
	}

	public void setFLAG_SERVICE(Boolean FLAG_SERVICE) {
		this.FLAG_SERVICE = FLAG_SERVICE;
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		if (mHelper.getNoteRowCount() == 0) {
			// Si es la primera vez que ejecuto
			FLAG_PRIMERAVEZ = true;
		}
		if (image_button != null) {
			image_button.setVisibility(View.GONE);
		}
		if (pg_Noteloading != null) {
			pg_Noteloading.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected void onProgressUpdate(ProgressDialog... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}

	private void updateData() {
		SQLiteDatabase dataBase = mHelper.getWritableDatabase();
		if (!dataBase.isOpen()) {
			dataBase = new DatabaseHandler(context).getWritableDatabase();
		}
		if (Integer.parseInt(noticias.get(0).getID()) > Integer
				.parseInt(mHelper.getLastNote().getID())) {
			for (int i = 0; i < noticias.size(); i++) {
				if (mHelper.getSimpleNote(Integer.parseInt(noticias.get(i)
						.getID())) == null) {
					// esta nota no esta, agregarla...
					System.out.println("Agrego: ID NOTA: "
							+ noticias.get(i).getID());
					Noticia n = noticias.get(i);
					mHelper.addNota(n);
					prefs = PreferenceManager
							.getDefaultSharedPreferences(context);
					if (FLAG_SERVICE
							&& prefs.getBoolean("cbp_note_polling", true)) {

						NoteNotification notificar = new NoteNotification(
								context,
								"Hay nuevas notas en EstasEnPosse.com",
								"Nueva nota en EstasEnPosse.com", "NOTA");
					}

				} else {
					System.out.println("Nota ya existe "
							+ noticias.get(i).getID());
				}
			}
		} else {
			System.out.println("No hay notas para agregar");
		}
		if (dataBase.isOpen()) {
			mHelper.cleanNotes(dataBase);
		} else {
			dataBase = new DatabaseHandler(context).getWritableDatabase();
			mHelper.cleanNotes(dataBase);
		}
		if (dataBase.isOpen()) {
			dataBase.close();
		}
	}

	private void updatePublicity() {
		SQLiteDatabase dataBase = mHelper.getWritableDatabase();
		if (!dataBase.isOpen()) {
			dataBase = new DatabaseHandler(context).getWritableDatabase();
		}
		for (int i = 0; i < publicidades.size(); i++) {
			if (mHelper.getPublicity(publicidades.get(i).getId()) == null) {
				// esta publi no esta, agregarla...
				Publicity p = publicidades.get(i);
				int ID = publicidades.get(i).getId();
				System.out.println("Agrego ID PUBLICIDAD: " + ID);
				mHelper.addPublicity(p);
			} else {
				mHelper.updatePublicityData(publicidades.get(i));
				System.out.println("Update publi: "
						+ publicidades.get(i).getId());
			}
		}
		dataBase.close();
	}

	private void saveData() {

		for (int i = 0; i < noticias.size(); i++) {
			Noticia n = noticias.get(i);
			int ID = Integer.parseInt(noticias.get(i).getID());
			System.out.println("Almaceno: ID NOTA: " + ID);

			mHelper.addNota(n);
		}

	}

	private void savePublicity() {

		for (int i = 0; i < publicidades.size(); i++) {
			Publicity p = publicidades.get(i);
			int ID = publicidades.get(i).getId();
			System.out.println("Almaceno: ID PUBLICIDAD: " + ID);

			mHelper.addPublicity(p);

		}
	}

}
